//
//  LockSetViewController.m
//  IntelligentHousehold
//
//  Created by wmwMAC on 17/6/23.
//  Copyright © 2017年 Cassie. All rights reserved.
//

#import "LockSetViewController.h"

#import "LogInViewController.h"

#import "LockSetTableViewCell.h"
#import "LockOpenSetTableViewCell.h"

#import "SetPhoneLockRecordViewController.h"
#import "SetRedLineViewController.h"
#import "WhiteListViewController.h"//白名单
#import "SetSafetyTimeViewController.h"//设置安全监测时间
#import "AlarmLearnViewController.h"//报警学习
#import "DoorLockViewController.h"//设置门锁号码
#import "ReportEmergencyViewController.h"


//#import "DDViewController.h"

#import <MessageUI/MessageUI.h>//系统短信


static NSString *identifier = @"LockSetTableViewCell";
static NSString *openIdentifier = @"LockOpenSetTableViewCell";
@interface LockSetViewController ()<UITableViewDelegate,UITableViewDataSource,LockOpenSetTableViewCellDelegate,MFMessageComposeViewControllerDelegate>
{
    NSArray *CellNameArr;
    NSArray *imgArr;
    
    NSString *msgTitle;//发送短信内容
    BOOL DoorIsOn;
    BOOL AlertIsOn;
    
    
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableDictionary *dateDIc;//
@property (nonatomic, strong) NSDictionary *saveDic;
@end

@implementation LockSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"开锁设置";
    
    CellNameArr = @[@"查询/设置白名单",@"查询电话开锁记录",@"设置开门短信回复",@"设置告警回复短信",@"设置红外线/门磁报警",@"告警记录",@"报警学习",@"恢复出厂设置"];
    imgArr = @[@"sz_gywm",@"kssz_ksjlu",@"kssz_hfcsz",@"kssz_jghfdx",@"kssz_dcbj",@"jg",@"kssz_bjxx",@"kssz_hfcsz"];
    
    self.dateDIc = [NSMutableDictionary dictionary];
    
    
    
    [self addTableviewUI];
}
- (void)addTableviewUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight-kNavigationBarHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = BaseColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"LockSetTableViewCell" bundle:nil] forCellReuseIdentifier:identifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"LockOpenSetTableViewCell" bundle:nil] forCellReuseIdentifier:openIdentifier];
    [self.view addSubview:self.tableView];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 3){
        return 3;
    }else{
        return 2;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 2) {
        LockOpenSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:openIdentifier forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.tag = 2000+indexPath.row;
        
        cell.titleLabel.text = CellNameArr[(indexPath.section-1)*2+indexPath.row];
        cell.titleImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",imgArr[(indexPath.section-1)*2+indexPath.row]]];
        
        if (indexPath.row==0) {
            NSString *doorStr = [self.dateDIc objectForKey:@"door"];
            cell.isOn = doorStr.integerValue;
        }else{
            NSString *gaojingStr = [self.dateDIc objectForKey:@"gaojing"];
            cell.isOn = gaojingStr.integerValue;
        }
        
        return cell;
        
        
    }else{
        LockSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        if (indexPath.section == 0) {
            cell.titleLabel.text = @"设置门锁号码";
          
            self.saveDic = [SaveDataMethord readLoginData];
            NSString *lockNumberStr = [self.saveDic objectForKey:@"locknumber"];
            NSLog(@"%@",lockNumberStr);
            
            if (lockNumberStr.length > 3) {
                cell.detailLable.text = lockNumberStr;
            }else{
                cell.detailLable.text = @"";
            }
            
            cell.titleImage.image = [UIImage imageNamed:@"kssz_szmshm"];
        }else{
            
            if (indexPath.row == 2) {
                
                cell.titleLabel.text = @"设置安检测时间";
                cell.titleImage.image = [UIImage imageNamed:@"kssz_jcsj"];
            }else{
                cell.titleLabel.text = CellNameArr[(indexPath.section-1)*2+indexPath.row];
                cell.titleImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",imgArr[(indexPath.section-1)*2+indexPath.row]]];
            }
            
            
        }
        return cell;
        
    }
    
    return nil;
    
    
}
-(void)lockOpenSetPassOn:(BOOL)isOne index:(NSInteger)index{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *lockNumberStr = saveDic[@"locknumber"];
    
    if (lockNumberStr.length>1) {
        
        if ([[saveDic objectForKey:@"type"] integerValue] == 0) {
            if (index == 2000) {//设置开门短信回复
                
                if (isOne) {
                    msgTitle = @"setopenanswer";//开启回复
                }else{
                    msgTitle = @"clearopenanswer";//关闭回复
                }
                [self sendMsg];
                DoorIsOn = isOne;
                
            }else{//告警短信
                if (isOne) {
                    msgTitle = @"setalarmsms";//开启告警回复
                }else{
                    msgTitle = @"clearalarmsms";//关闭回复
                }
                [self sendMsg];
                AlertIsOn = isOne;
            }
        }else{
            [MBProgressHUD showText:@"当前账号没有权限!"];
            [self.tableView reloadData];
            
        }
        
        
    }else{
        [MBProgressHUD showText:@"请设置门锁号码!"];
        [self.tableView reloadData];
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
        
    }else{
        return 0.01;
        
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = BaseColor;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    footview.backgroundColor = BaseColor;
    
    return footview;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *lockNumberStr = saveDic[@"locknumber"];
    
    
    if (indexPath.section == 0) {
        DoorLockViewController *VC = [[DoorLockViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
        
    }
    if (indexPath.section == 1) {
        
        if (lockNumberStr.length>1) {
            
            if (indexPath.row == 0) {//查询白名单
                
                WhiteListViewController *whitListVC = [[WhiteListViewController alloc] init];
                [self.navigationController pushViewController:whitListVC animated:YES];
                
            }else{//查询电话开锁记录
                
                if ( [[saveDic objectForKey:@"type"] integerValue] == 0) {//管理员
                    SetPhoneLockRecordViewController *vc = [[SetPhoneLockRecordViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    [MBProgressHUD showText:@"当前账号没有权限!"];
                }
                
            }
            
            
        }else{
            [MBProgressHUD showText:@"请设置门锁号码"];
        }
        
        
        
    }
    
    if (indexPath.section == 3) {
        
        if (lockNumberStr.length>1) {
            if ( [[saveDic objectForKey:@"type"] integerValue] == 0) {//管理员
                if (indexPath.row == 0) {
                    
                    SetRedLineViewController *vc = [[SetRedLineViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                    
                }else if (indexPath.row == 1){
                    
                    ReportEmergencyViewController *vc = [[ReportEmergencyViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                }else{
                    SetSafetyTimeViewController *vc = [[SetSafetyTimeViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
            }else{
                [MBProgressHUD showText:@"当前账号没有权限!"];
            }
        }else{
            [MBProgressHUD showText:@"请设置门锁号码"];
        }
        
        
    }
    if (indexPath.section == 4) {
        
        if (lockNumberStr.length>1) {
            
            if ( [[saveDic objectForKey:@"type"] integerValue] == 0) {//管理员
                
                if (indexPath.row == 0) {
                    
                    AlarmLearnViewController *vc = [[AlarmLearnViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                    
                }else{
                    
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"恢复出厂设置" message:@"信息会清空" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alertController addAction:cancelAction];
                    
                    UIAlertAction *contentAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                        
                        msgTitle = @"reset";
                        [self sendMsg];
                        
                    }];
                    [alertController addAction:contentAction];
                    
                    [self presentViewController:alertController animated:YES completion:^{
                        
                    }];
                    
                }
                
            }else{
                [MBProgressHUD showText:@"当前账号没有权限!"];
            }
            
        }else{
            
            [MBProgressHUD showText:@"请设置门锁号码"];
        }
        
        
    }
    
    
}
#pragma mark 开门短信回复
-(void)setComDuanxin:(NSString *)isOn{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:isOn forKey:@"type"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];
    
    NSString *timeStr = [BasePublicMethord getTimeDataPointString];
    [parameDic setObject:timeStr forKey:@"time"];
    
    
    
    if (!isOn) {
        [parameDic setObject:@"setopenanswer" forKey:@"command"];//开启setopenanswer 关闭clearopenanswer
    }else{
        [parameDic setObject:@"setopenanswer" forKey:@"command"];
        
    }
    
    
    NSString *url = [NSString stringWithFormat:COMDUANXIN,RealmName];
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        NSString *msgStr = [responseObject objectForKey:@"msg"];
        
        if ([msgStr isEqualToString:@"success"]) {
            [MBProgressHUD showText:@"修改成功"];
        }else{
            [MBProgressHUD showText:msgStr];
            
        }
        
        [self getShezhi];
        
    } failure:^(NSError *error) {
        
    }];
    
    
}
#pragma mark 告警短信回复

-(void)setComggaojing:(NSString *)isOn{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:isOn forKey:@"type"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];
    
    NSString *timeStr = [BasePublicMethord getTimeDataPointString];
    [parameDic setObject:timeStr forKey:@"time"];
    
    if (!isOn) {
        [parameDic setObject:@"setalarmsms" forKey:@"command"];//开启setalarmsms 关闭clearalarmsms
    }else{
        [parameDic setObject:@"clearalarmsms" forKey:@"command"];
        
    }
    
    
    NSString *url = [NSString stringWithFormat:COMGAOJING,RealmName];
    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        NSString *msgStr = [responseObject objectForKey:@"msg"];
        
        if ([msgStr isEqualToString:@"success"]) {
            [MBProgressHUD showText:@"修改成功"];
        }else{
            [MBProgressHUD showText:msgStr];
            
        }
        [self getShezhi];
    } failure:^(NSError *error) {
        
    }];
    
    
}


-(void)getShezhi{
    NSString *url = [NSString stringWithFormat:CHAXUNSHEZHI,RealmName];
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];
    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        NSString *msgStr = [responseObject objectForKey:@"msg"];
        if ([msgStr isEqualToString:@"success"]) {
            
            self.dateDIc = [NSMutableDictionary dictionaryWithDictionary:responseObject].mutableCopy;
            [self.tableView reloadData];
            
        }else{
            [MBProgressHUD showText:msgStr];
        }
        
        
    } failure:^(NSError *error) {
        
    }];
    
    
}
//恢复出厂设置
-(void)RestoreFactory{
    NSString *url = [NSString stringWithFormat:RESTOREFACTORY,RealmName];
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];
    
    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if ([[responseObject objectForKey:@"msg"] isEqualToString:@"success"]) {
            
            
            
            [MBProgressHUD showText:@"恢复出厂设置成功"];
            
            NSDictionary *saveDic = [SaveDataMethord readLoginData];
            NSMutableDictionary *tempDIc = saveDic.mutableCopy;
            [tempDIc setObject:@"" forKey:@"locknumber"];
            // 修改登录保存
            //存储信息
            [SaveDataMethord SaveLoginDataToLocationWithDic:tempDIc.mutableCopy];
            
            NSDictionary *ss = [SaveDataMethord readLoginData];
            NSLog(@"%@",ss);
            
            [self getShezhi];
            
        }else{
            [MBProgressHUD showText:[responseObject objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark -------------- 发送短信 ----------------
-(void)sendMsg{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *locknumberStr = saveDic[@"locknumber"];
    //    telStr = @"10086";
    
    
    if (locknumberStr.length>2) {
        [self showMessageView:[NSArray arrayWithObjects:locknumberStr, nil] title:nil body:msgTitle];
    }else{
        [MBProgressHUD showText:@"请先设置门锁号码"];
    }
    
    
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if( [MFMessageComposeViewController canSendText] )
    {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
        controller.messageComposeDelegate = self;
        
        
        [self presentViewController:controller animated:YES completion:nil];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"该设备不支持短信功能 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark - MFMessageComposeViewController

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (result) {
        if (MessageComposeResultSent) {//短信发送成功
            
            //            if ([msgTitle isEqualToString:@"queryphone"]) {//白名单
            //                WhiteListViewController *whitListVC = [[WhiteListViewController alloc] init];
            //                [self.navigationController pushViewController:whitListVC animated:YES];
            //            }else if ([msgTitle isEqualToString:@"queryhistory"]){//开锁记录
            //                SetPhoneLockRecordViewController *vc = [[SetPhoneLockRecordViewController alloc] init];
            //                [self.navigationController pushViewController:vc animated:YES];
            //            }else
            if ([msgTitle isEqualToString:@"setopenanswer"] || [msgTitle isEqualToString:@"clearopenanswer"]){//开门回复
                [self setComDuanxin:[NSString stringWithFormat:@"%d",DoorIsOn]];
            }else if ([msgTitle isEqualToString:@"reset"]){// 恢复出厂
                [self RestoreFactory];
                
            }else if ([msgTitle isEqualToString:@"clearalarmsms"] || [msgTitle isEqualToString:@"setalarmsms"]){// 告警短信
                [self setComggaojing:[NSString stringWithFormat:@"%d",AlertIsOn]];
            }
        }
    }else{
        [self getShezhi];
    }
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getShezhi];
    [self mianLogin];
}

-(void)mianLogin{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    NSString *url = [NSString stringWithFormat:MIANLOGIN,RealmName];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"tell"] forKey:@"tell"];
    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        [SaveDataMethord cleanloginData];//清除登录记录
        
        NSDictionary *dataDic = [NSDictionary dictionaryWithDictionary:responseObject];
        //存储信息
        [SaveDataMethord SaveLoginDataToLocationWithDic:dataDic.mutableCopy];
        self.saveDic = [SaveDataMethord readLoginData];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
